﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using StyleMVVM.View;

namespace StyleMVVM.ViewModel
{
	/// <summary>
	/// Inherit from this class when the ViewModel is used for a Window class
	/// </summary>
	public class WindowViewModel : BaseViewModel, IViewAware, IWindowViewModel
	{
		private object navigationParameter;
		private WeakReference<FrameworkElement> view;
		private string title;

		/// <summary>
		/// Title for the window
		/// </summary>
		public virtual string Title
		{
			get { return title; }
			set { SetProperty(ref title, value); }
		}

		/// <summary>
		/// The View associated with this ViewModel
		/// </summary>
		public virtual FrameworkElement View
		{
			get
			{
				FrameworkElement element = null;

				if (view != null)
				{
					if (!view.TryGetTarget(out element))
					{
						view = null;
					}
				}

				return element;
			}
			set
			{
				view = new WeakReference<FrameworkElement>(value);

				OnPropertyChanged();
			}
		}

		/// <summary>
		/// Called when the window has closed
		/// </summary>
		public virtual void Closed()
		{
		}

		/// <summary>
		/// Called when the window is closing.
		/// </summary>
		/// <param name="eventArgs"></param>
		public virtual void Closing(CancelEventArgs eventArgs)
		{
		}

		public virtual void Opened()
		{
		}

		/// <summary>
		/// Call to close the window
		/// </summary>
		public virtual void Close()
		{
			Window window = View as Window;

			if (window != null)
			{
				window.Close();
			}
		}

		public virtual object NavigationParameter
		{
			get { return navigationParameter; }
			set { SetProperty(ref navigationParameter, value); }
		}
	}
}